from mysite.g_novel.models import *
from mysite.g_novel.forms import *

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib import auth

import datetime, random, urllib
# Create your views here.
chars = range(48, 123)
chars.remove(58)
chars.remove(59)
chars.remove(91)
chars.remove(92)
chars.remove(93)
chars.remove(94)
chars.remove(95)
chars.remove(96)

logfile="logging2.txt"


def random_code():
	s=''
	for i in range(0, 100):
		s+= chr(random.choice(chars))
	return s
		

	
def home(request):
	#f=open(logfile, 'a')
	if request.user.is_authenticated():
		user = request.user
		code="authenticated user"
		authentic=True
	elif request.session.get('visitor-code'):
		#f.write("inside session.get('visitor-code')\n")
		try:
			user = SemiUser.objects.filter(cookie_code=request.session['visitor-code'])
			code = request.session['visitor-code']
			#f.write("%s\n" % code)
		except Exception, e:
			#generate a new visitor code, since it has either been tampered with, or corrupted. 
			#f.write("exception %s\n" % e)
			request.session['visitor-code']=random_code()
			user = SemiUser(cookie_code=request.session['visitor-code'])
			user.save()
			code="corrupted user"
		code=request.session['visitor-code']
	else:
		#f.write("new user, generating new code\n")
		#new user. 
		request.session['visitor-code']=random_code()
		user = SemiUser.objects.create(cookie_code=request.session['visitor-code'])
		user.save()
		code="new user"

	css = 'mycss.css'
	latest_list=Issue.objects.all() #three issues
	#f.close()
	return render_to_response('comics/index.html', locals())
	
def new_series(request):
	if request.user.is_authenticated():
		user = request.user
		authentic=True
		css = 'mycss.css'
		if request.method=='POST':
			form = SeriesForm(request.POST, auto_id=True)
			form.is_valid()
			new_ser = Series.objects.create(ser_title=cleaned['series_title'], author=user)
			new_ser.save()
			saved=True
			title=form['series_title']
			return render_to_response('comics/new_series.html', locals())
				
		else:
			
			form = SeriesForm(auto_id=True)
			return render_to_response('comics/new_series.html', locals())
	else:
		css = 'mycss.css'
		return render_to_response('comics/notvalid.html', locals())
	
def new_issue(request):
	if request.user.is_authenticated():
		user = request.user
		authentic=True
		css = 'mycss.css'
		if request.method=='POST':
			form = IssueForm(request.POST, auto_id=True)
			if form.is_valid():
				found = 0
				cleaned=form.cleaned_data
				for ser in user.series_set.all():
					if ser == cleaned['series']:
						found =1
						break
				if found == 1:
					new_ish = Issue.objects.create(ish_title=cleaned['issue_title'], series=cleaned['series'], pub_date=cleaned['date'])
					new_ish.save()
					saved=True
				else:
					notyours=1
			return render_to_response('comics/new_issue.html', locals())
				
		else:
			
			form = IssueForm(auto_id=True)
			return render_to_response('comics/new_issue.html', locals())
	else:
		css = 'mycss.css'
		return render_to_response('comics/notvalid.html', locals())
		
def new_page(request):
	if request.user.is_authenticated():
		user = request.user
		authentic=True
		css= 'mycss.css'
		if request.method=='POST':
			form = PageForm(request.POST, request.FILES, auto_id=True)
			if form.is_valid():
				cleaned = form.cleaned_data
				found = 0
				for ser in user.series_set.all():
					for ish in ser.issue_set.all():
						if ish==cleaned['issue']:
							found = 1
							break
				if found==1:
					pg = cleaned['pg']
					new_page = Page.objects.create(issue=cleaned['issue'],  page_number=cleaned['pg_number'], pub_date=cleaned['date'])
					new_page.save_fle_file(pg.filename, pg.content)
					new_page.save()
					saved=True
				else:
					notyours=1
			else:
				mistake=1
			return render_to_response('comics/new_page.html', locals())
		else:
			form = PageForm(auto_id=True)
			return render_to_response('comics/new_page.html', locals())
	else:
		css = 'mycss.css'
		return render_to_response('comics/notvalid.html', locals())
		
def view_series(request, series_name):
	#f=open(logfile, 'a')
	#f.write('inside view_series\n')
	name = urllib.unquote(series_name)
	series = Series.objects.get(ser_title=name)
	issue_list=series.issue_set.all()
	if request.user.is_authenticated():
		user = request.user
		authentic=True
	elif request.session.get('visitor-code'):
		authentic=False
		#f.write("inside session.get('visitor-code')\n")
		try:
			code = request.session['visitor-code']
			user = SemiUser.objects.get(cookie_code=code)
			#f.write("user:"+str(user)+'\n')
			#f.write("%s\n" % code)
		except Exception, e:
			#generate a new visitor code, since it has either been tampered with, or corrupted. 
			#f.write("exception %s\n" % e)
			request.session['visitor-code']=random_code()
			user = SemiUser(cookie_code=request.session['visitor-code'])
			user.save()
			code="corrupted user"
		#code=request.session['visitor-code']
	else:
		authentic=False
		#f.write("new user, generating new code\n")
		#new user. 
		request.session['visitor-code']=random_code()
		user = SemiUser(cookie_code=request.session['visitor-code'])
		user.save()
		code="new user"
	bookmarks = user.bookmarks_set.all()
	if len(bookmarks)==0:
		if not authentic:
			bookmarks = BookMarks.objects.create(semiuser=user)
		else:
			bookmarks = BookMarks.objects.create(user=user)
	else:
		bookmarks=bookmarks[0]
	bookmarks.save()
	css = 'mycss.css'
	return render_to_response('comics/view_series.html', locals())
	
def view_issue(request, series_name, issue_name):
	name = urllib.unquote(series_name)
	ish_name = urllib.unquote(issue_name)
	series = Series.objects.get(ser_title=name)
	issue=series.issue_set.get(ish_title=ish_name)
	pages = issue.page_set.all()[:6]
	if request.user.is_authenticated():
		user = request.user
		authentic=True
	css = 'mycss.css'
	return render_to_response('comics/view_issue.html', locals())

	
def next_image(request, series_name, issue_name, panel_number):
	#f=open(logfile, 'a')
	name = urllib.unquote(series_name)
	#f.write(name+'\n')
	ish_name = urllib.unquote(issue_name)
	#f.write(issue_name+'\n')
	series = Series.objects.get(ser_title=name)
	#f.write(unicode(series)+'\n')
	issue=series.issue_set.get(ish_title=ish_name)
	#f.write(issue+'\n')
	pages = issue.page_set.all()
	#f.write(panel_number+'\n')
	p= pages[int(panel_number)+1].get_absolute_image_url()
	i='<img rel="'+p+'" title="'+str(int(panel_number)+1)+":"+str(int(panel_number)+1)+'" src="'+p+' />'
	#f.write(i+'\n')
	#f.close()
	return HttpResponse(i, mimetype="text/html")
	
	
	

	
	
